<!--  -->
<template>
  <div>
    <el-table :data="tableData">
      <el-table-column width="470px">
        <template slot-scope="scope">
          <el-checkbox
            :key="scope.row.id"
            v-model="scope.row.isChecked"
            @change="changeCheck(scope.row)"
          >
            <span v-show="!scope.row.isEdit" style="margin-left: 10px">{{
              scope.row.msg
            }}</span>
            <input
              v-show="scope.row.isEdit"
              type="text"
              :value="scope.row.msg"
              @keyup.enter="displace_title(scope.row, $event)"
              @blur="displace_title(scope.row, $event)"
              :ref="'ipt' + scope.row.id"
              id="ipt"
            />
          </el-checkbox>
        </template>
      </el-table-column>

      <el-table-column>
        <template slot-scope="scope">
          <el-button size="mini" @click="edit(scope.$index, scope.row)"
            >Edit</el-button
          >
          <el-button
            size="mini"
            type="danger"
            @click="del(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
export default {
  name: "list",
  data() {
    return {
      tableData: JSON.parse(localStorage.getItem("todoData")),
      finishedNum: 0,
    };
  },
  //如果有emit 记得emit把事件总线放在mounted 确保on先定义了
  mounted() {
    this.changeCheck();
  },
  created() {
    //接受新增的事件bus
    this.$bus.$on("newAdd_data", (add_msg) => {
      // console.log(add_msg);
      this.add(add_msg);
    });
    //接收全选事件
    this.$bus.$on("allCheckedClick", (checked) => {
      this.tableData = this.tableData.filter((objItem) => {
        if (objItem.isChecked != checked) {
          objItem.isChecked = checked;
        }
        return objItem;
      });
    });
    //接受清除事件
    this.$bus.$on("clearAll", () => {
      this.$confirm("此操作将永久清除事件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let len = this.tableData.length;
          this.tableData = this.tableData.filter((objItem) => {
            return !objItem.isChecked;
          });
          //长度没变 说明没有可以删除的
          if (len === this.tableData.length) {
            return this.$message({
              message: "没有完成了的",
              duration: 1500,
            });
          }
          //长度变了说明删除了 删除了计算全选
          this.changeCheck();
          this.$message({
            message: "清除成功",
            type: "success",
            duration: 1500,
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
            duration: 1500,
          });
        });
    });
  },
  methods: {
    emitNum() {
      //传出数量
      this.$bus.$emit(
        "finished_allNum",
        this.finishedNum,
        this.tableData.length
      );
    },
    add(msg) {
      this.tableData.unshift(msg);
    },
    changeCheck(row) {
      if (row) {
        // console.log("row", row.id, row.isChecked);
        this.tableData = this.tableData.filter((objItem) => {
          if (objItem.id === row.id) {
            objItem.isChecked = row.isChecked;
          }
          return objItem;
        });
      }
      //判断是不是全选了
      let notAll = true;
      if (this.tableData.length > 0) {
        notAll = this.tableData.some((objItem) => {
          return !objItem.isChecked;
        });
      }
      //传出全选信号
      this.$bus.$emit("allChecked", !notAll);

      //计算选择的数量
      this.finishedNum = 0;
      this.tableData.forEach((objItem) => {
        objItem.isChecked === true && this.finishedNum++;
      });
      //数量
      this.emitNum();
    },
    del(index, row) {
      this.$confirm("此操作将永久删除该事件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.tableData.some((objItem, i) => {
            if (objItem.id === row.id) {
              this.tableData.splice(i, 1);
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              return true;
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    edit(index, row) {
      //使用set才会将后加入的数据进行监听
      if (!row.hasOwnProperty("isEdit")) {
        this.$set(row, "isEdit", true);
      } else {
        this.tableData = this.tableData.filter((objItem) => {
          if (objItem.id === row.id) {
            objItem.isEdit = true;
          }
          return objItem;
        });
      }
      //无效（因为input还没放到页面）
      this.$nextTick(() => {
        //告诉你为什么这样不可以 因为命名为ipt后 所有的input都是这个名字
        //this.$refs["ipt"]的话获取到的是最后一个input框 也就是只有最后一个才能获取焦点
        //解决方法：定义ef时加上唯一的标志 如ipt+id,这样就能唯一标识了
        this.$refs["ipt" + row.id].focus();
        // document.querySelector("#ipt").focus();
      });
    },
    displace_title(row, e) {
      if (e.target.value.trim() === "") return alert("不可为空!");

      this.tableData = this.tableData.filter((objItem) => {
        if (objItem.id === row.id) {
          //修改值 值通过$event.target获取
          objItem.msg = e.target.value.trim();
          objItem.isEdit = false;
        }
        return objItem;
      });
    },
  },
  updated() {
    console.log("update");
    //全选
    this.changeCheck();
    // 本地（使用watch也可以）
    localStorage.setItem("todoData", JSON.stringify(this.tableData));
  },
  beforeDestroy() {
    this.$bus.$off("newAdd_data");
    this.$bus.$off("allCheckedClick");
    this.$bus.$off("allCheckedCclearAllick");
  },
};
</script>

<style  scoped>
/**==================================动漫================================= */
/* vue transition使用时类名的规范 v为name过度名，默认是v ,这里设置name=“vv”*/
.vv-enter-active {
  animation: itguigu 0.5s linear;
}
.vv-leave-active {
  animation: itguigu 0.5s reverse linear;
}

@keyframes itguigu {
  0% {
    transform: translateX(-100%);
  }
  50% {
    transform: translateX(-50%);
    background-color: rgb(216, 60, 60);
  }
  100% {
    transform: translateX(0);
    background-color: red;
  }
}
</style>
